import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import '../app_data_manager.dart';

class MonthlyLineChart extends StatefulWidget {
  const MonthlyLineChart({super.key});

  @override
  State<MonthlyLineChart> createState() => _MonthlyLineChartState();
}

class _MonthlyLineChartState extends State<MonthlyLineChart> {
  int selectedMonth = DateTime.now().month;
  double threshold = 0.0;
  final TextEditingController _thresholdController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _thresholdController.text = '0';
  }

  @override
  void dispose() {
    _thresholdController.dispose();
    super.dispose();
  }

  List<FlSpot> _getMonthData() {
    final year = DateTime.now().year;
    final daysInMonth = DateTime(year, selectedMonth + 1, 0).day;
    final List<FlSpot> spots = [];

    for (int day = 1; day <= daysInMonth; day++) {
      final date = '$year-${selectedMonth.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}';
      final score = AppDataManager().getDisciplineScore(date);
      spots.add(FlSpot(day.toDouble(), score.toDouble()));
    }

    return spots;
  }

  // 计算Y轴范围
  (double, double) _calculateYAxisRange(List<FlSpot> spots) {
    if (spots.isEmpty) return (-10.0, 10.0);  // 默认范围

    // 找出数据中的最大值和最小值
    double minY = spots.map((spot) => spot.y).reduce((a, b) => a < b ? a : b);
    double maxY = spots.map((spot) => spot.y).reduce((a, b) => a > b ? a : b);

    // 考虑阈值线
    minY = minY < threshold ? minY : threshold;
    maxY = maxY > threshold ? maxY : threshold;

    // 确保至少包含0
    minY = minY < 0 ? minY : 0;
    maxY = maxY > 0 ? maxY : 0;

    // 增加一些边距
    final padding = (maxY - minY).abs() * 0.1;  // 10%的边距
    minY = minY - padding;
    maxY = maxY + padding;

    // 如果范围太小，使用默认范围
    if ((maxY - minY).abs() < 5) {
      return (-10.0, 10.0);
    }

    // 将范围调整为整数
    return (minY.floor().toDouble(), maxY.ceil().toDouble());
  }

  @override
  Widget build(BuildContext context) {
    final spots = _getMonthData();
    final daysInMonth = DateTime(DateTime.now().year, selectedMonth + 1, 0).day;
    final aboveThresholdDays = spots.where((spot) => spot.y >= threshold).length;
    final percentage = (aboveThresholdDays / daysInMonth * 100).toStringAsFixed(1);

    // 计算Y轴范围
    final (minY, maxY) = _calculateYAxisRange(spots);
    // 计算合适的Y轴间隔
    final interval = ((maxY - minY) / 10).ceil().toDouble();

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '月度自律趋势',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                DropdownButton<int>(
                  value: selectedMonth,
                  items: List.generate(12, (index) => index + 1)
                      .map((month) => DropdownMenuItem(
                            value: month,
                            child: Text('$month月'),
                          ))
                      .toList(),
                  onChanged: (value) {
                    if (value != null) {
                      setState(() => selectedMonth = value);
                    }
                  },
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                const Text('目标阈值: '),
                SizedBox(
                  width: 60,
                  child: TextField(
                    controller: _thresholdController,
                    keyboardType: TextInputType.number,
                    onChanged: (value) {
                      final newThreshold = double.tryParse(value) ?? 0.0;
                      setState(() => threshold = newThreshold);
                    },
                  ),
                ),
                const SizedBox(width: 16),
                Text(
                  '达标率: $percentage%',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.green,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: LineChart(
                LineChartData(
                  minY: minY,
                  maxY: maxY,
                  gridData: FlGridData(
                    show: true,
                    drawVerticalLine: true,
                    horizontalInterval: interval,
                    verticalInterval: 5,
                    getDrawingHorizontalLine: (value) {
                      return FlLine(
                        color: Colors.grey.withOpacity(0.2),
                        strokeWidth: 1,
                      );
                    },
                  ),
                  titlesData: FlTitlesData(
                    leftTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        interval: interval,
                        reservedSize: 35,
                        getTitlesWidget: (value, meta) {
                          return Text(
                            value.toInt().toString(),
                            style: const TextStyle(
                              color: Colors.grey,
                              fontSize: 12,
                            ),
                          );
                        },
                      ),
                    ),
                    bottomTitles: AxisTitles(
                      sideTitles: SideTitles(
                        showTitles: true,
                        interval: 5,
                        getTitlesWidget: (value, meta) {
                          return Text(
                            value.toInt().toString(),
                            style: const TextStyle(
                              color: Colors.grey,
                              fontSize: 12,
                            ),
                          );
                        },
                      ),
                    ),
                    rightTitles: AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                    topTitles: AxisTitles(
                      sideTitles: SideTitles(showTitles: false),
                    ),
                  ),
                  borderData: FlBorderData(
                    show: true,
                    border: Border(
                      bottom: BorderSide(color: Colors.grey.withOpacity(0.4)),
                      left: BorderSide(color: Colors.grey.withOpacity(0.4)),
                    ),
                  ),
                  lineBarsData: [
                    LineChartBarData(
                      spots: spots,
                      isCurved: true,
                      color: Colors.blue,
                      barWidth: 2,
                      isStrokeCapRound: true,
                      dotData: FlDotData(show: true),
                      belowBarData: BarAreaData(
                        show: true,
                        color: Colors.blue.withOpacity(0.1),
                      ),
                    ),
                    LineChartBarData(
                      spots: [
                        FlSpot(1, threshold),
                        FlSpot(daysInMonth.toDouble(), threshold),
                      ],
                      isCurved: false,
                      color: Colors.red,
                      barWidth: 1,
                      dashArray: [5, 5],
                      dotData: FlDotData(show: false),
                    ),
                    LineChartBarData(
                      spots: [
                        FlSpot(1, 0),
                        FlSpot(daysInMonth.toDouble(), 0),
                      ],
                      isCurved: false,
                      color: Colors.grey.withOpacity(0.5),
                      barWidth: 1,
                      dotData: FlDotData(show: false),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
} 